/**
 * 根据指定颜色修改图片颜色
 * @param imgUrl 图片url
 * @param color 主题颜色
 * @returns Promise 修改后的图片url
 */
export const changeImageColor = (imgUrl: string, color = "#3388ff"): Promise<string> => {
    return new Promise((resolve, reject) => {
        let threshold = 114; //默认颜色阀值 为 114 －>和默认图相关
        let img = new Image();
        img.src = imgUrl;
        let newR = parseInt("0x" + color.substring(1, 3));
        let newG = parseInt("0x" + color.substring(3, 5));
        let newB = parseInt("0x" + color.substring(5, 7));
        img.crossOrigin = ''
        //图片加载后进行处理
        img.onload = () => {
            let width = img.width, height = img.height, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
            canvas.width = width;
            canvas.height = height;
            // 将源图片复制到画布上
            ctx.drawImage(img, 0, 0, width, height);
            // 获取画布的像素信息
            let imageData = ctx.getImageData(0, 0, width, height)
            let data = imageData.data;

            // 对像素集合中的单个像素进行循环，每个像素是由4个通道组成，所以要注意
            let i = 0;

            
            while (i < data.length) {
                let r = data[i++],
                    g = data[i++],
                    b = data[i++],
                    a = data[i++];
                //计算透明度
                let alp = (255 - r) / (255 - threshold);
                //判断是否透明
                let isTransparent = r == 255 && g == 255 && b == 255 && a == 255;
                if (isTransparent) {
                    data[i - 1] = 0;
                } else {
                    data[i - 4] = newR;0  
                    data[i - 3] = newG;
                    data[i - 2] = newB;
                    // data[i - 1] = a !== 255 ? 255 - a : alp * 255; //处理透明的图片和不透明的图片
                }
            }
            // 将修改后的代码复制回画布中
            ctx.putImageData(imageData, 0, 0);
            // 图片导出为 png 格式
            let imgType = "png";
            let imgData = canvas.toDataURL(imgType);
            // 执行回调函数
            resolve(imgData)
        };
    })
}